<template>
  <div class="login-page">
    <div class="left"></div>
    <div class="login-container">
      <el-form
        :model="loginForm"
        status-icon
        :rules="rules"
        ref="loginForm"
        label-width="100px"
        class="demo-loginForm"
      >
        <h1 class="title">千锋管理系统</h1>
        <el-form-item label="用户名" prop="username">
          <el-input
            type="username"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from "../../api/index";
import {mapMutations} from "vuex"
export default {
  //登录逻辑的实现
  // 1.收集用户输入的username&password
  // 2.登录成功后，将后端返回的token存到本地，跳转到主页
  // 3.每次请求时，都携带token到请求头 authorization
  // 4.展示token校验通过后的正确的页面
  // 5.token校验不通过，跳转到登录页面
  data() {
    /**
     * jsDoc
     * @param {Object} rule  就是一个表单验证对象
     * @param {String} value 输入值
     * @param {Function} callback 校验通过不传参，不通过传参
     */
    var validateUsername = (rule, value, callback) => {
      console.log(rule);
      console.log(value);
      if (!value) {
        callback("请输入用户名");
      } else {
        callback();
      }
    };
    var validataPassword = (rule, value, callback) => {
      if (!value) {
        callback("请输入密码");
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "",
        password: "",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validataPassword, trigger: "blur" }],
      },
    };
  },
  methods: {
    ...mapMutations(["SET_userInfo"]),
    submitForm(formName) {
      console.log(this.$refs[formName]);
      this.$refs[formName].validate((valid) => {
        //valid=>本地验证通过
        if (valid) {
          //打开登录加载动画
          const loading = this.$loading({
            lock: true,
            text: "正在登录",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          //console.log(this.loginForm.username,this.loginForm.password);
          let { username, password } = this.loginForm;
          //发送登录请求
          login(username, password)
            .then((res) => {
              console.log(res);

              //服务器响应，关闭loading动画 
              loading.close()

              if (res.data.state) {
                this.$message.success('登录成功');
                console.log("用户名及密码正确");
                console.log(res);
                localStorage.setItem("stu_token", res.data.token);
                localStorage.setItem("stu-info",JSON.stringify(res.data.userInfo))
                this.SET_userInfo(res.data.userInfo)
                //更改vuex中state: {userInfo:{}}
                this.$router.push("/");
              } else {
                this.$message.error('登录失败');
              }
            })
            .catch((err) => {
              console.log(err);
            });
          //alert('submit!');
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style scoped>
.login-container {
  width: 25rem;
  height: 28rem;
  position: absolute;
  top: 20%;
  left: 60%;
  border-radius: 11px;
  background: rgba(0, 0, 0, 0.2);
  z-index: 7;
}
.title {
  text-align: center;
  margin: 70px 0 40px;
  color: #fff;
}
.el-button {
  width: 240px;
}
</style>